from fastapi import APIRouter
from app.utils.app_log import logger
from app.utils.request import RequestHandler

from app.schemas.system.aichat import ChatRequest, ChatResponse,ChatMessageResponse,ChatSessionResponse,ChatSessionUpdate
from app.services.system.aichat import aichat_service

from fastapi import Depends
from app.schemas.base.login import JWTPayload
from app.core.auth import get_current_user_required,get_current_superuser

from app.core.exceptions import BusinessError
from app.schemas.base.error_code import RESOURCE_NOT_FOUND


router = APIRouter()

@router.post("/aichat", response_model=dict)
async def chat_generate(
    request: ChatRequest,
    current_user: JWTPayload = Depends(get_current_user_required),
):
    """
    AI 聊天接口
    - 若传入 session_id → 继续该对话
    - 否则 → 创建新会话
    - 自动记录所有消息到数据库
    """
    try:
        # 强制绑定当前用户 ID 到请求中（安全加固）
        request.user_id = current_user.user_id

        logger.info(f"AI对话开始 (user_id={current_user.user_id}, session_id={request.session_id}): {request.user_message}")
        # 调用服务层
        chat_response: ChatResponse = await aichat_service.apply_chat(request, request.session_id)

        return RequestHandler.success(
            data=chat_response,
            message="AI对话生成成功",
            remarks="已根据历史上下文生成回复"
        )

    except Exception as e:
        logger.error(f"AI对话失败: {str(e)}")
        raise RequestHandler.server_error(message=f"AI对话失败: {str(e)}")


@router.get("/sessions", response_model=list[ChatSessionResponse])
async def get_chat_sessions(
    current_user: JWTPayload = Depends(get_current_user_required),
    limit: int = 20,
    offset: int = 0,
):
    """获取当前用户的所有对话会话列表"""
    sessions = await aichat_service.get_sessions_by_user(current_user.user_id, limit, offset)
    return [await aichat_service.to_chat_session_response(session) for session in sessions]


@router.get("/sessions/{session_id}/messages", response_model=list[ChatMessageResponse])
async def get_session_messages(
    session_id: int,
    current_user: JWTPayload = Depends(get_current_user_required),
    limit: int = 50,
):
    """获取指定会话的所有消息"""
    session = await aichat_service.get_session_by_id(session_id, current_user.user_id)
    if not session:
        raise BusinessError(RESOURCE_NOT_FOUND, details="会话不存在或无权限访问")

    messages = await aichat_service.history_service.get_messages_by_session(session_id, limit)
    return await aichat_service.to_chat_message_responses(messages)

@router.put("/sessions/{session_id}")
async def update_session(
    session_id: int,
    update_data: ChatSessionUpdate,
    current_user: JWTPayload = Depends(get_current_user_required),
):
    if update_data.id != session_id:
        raise RESOURCE_NOT_FOUND(RESOURCE_NOT_FOUND, details = "URL 中的 session_id 与请求体中的 id 不匹配")

    session = await aichat_service.get_session_by_id(session_id, current_user.user_id)
    if not session:
        raise BusinessError(RESOURCE_NOT_FOUND, details="会话不存在或无权限访问")

    updated = await aichat_service.session_service.update_session(session, update_data)
    return ChatSessionResponse.from_orm(updated)  # 如果你用 from_orm